package com.applink.sell_proof.database.table;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;

import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.database.EMarketingContentProvider;

public class ImageDBHelper {
	public static final String TABLE_NAME = "image_cache";
	public static final String ID = "record_id";

	public static final String ORIGINAL_PATH = "original_path";
	public static final String CACHED_PATH = "cached_path";

	public static final String SQL_EXCUTE = "CREATE TABLE " + TABLE_NAME + "("
			+ ID + " integer primary key AUTOINCREMENT," + ORIGINAL_PATH
			+ " text ," + CACHED_PATH + " text);";

	public static String getCachePath(String originalpath) {

		ContentResolver resolver = EMarketing.getInstance()
				.getApplicationContext().getContentResolver();

		Cursor cursor = resolver.query(
				EMarketingContentProvider.IMAGE_CONTENT_URI, null,
				ORIGINAL_PATH + "=?", new String[] { originalpath }, null);

		if (cursor != null) {
			try {
				if (cursor.moveToFirst()) {
					String result = cursor.getString(cursor
							.getColumnIndex(CACHED_PATH));

					if (!result.equals(""))
						return result;
				}
			} finally {
				cursor.close();
			}
		}
		return "";
	}

	public static void insertPaths(final String originalpath,
			final String cachepath) {

		new Thread() {
			@Override
			public void run() {
				ContentValues values = new ContentValues();
				ContentResolver resolver = EMarketing.getInstance()
						.getApplicationContext().getContentResolver();

				String checkCache = getCachePath(originalpath);

				if (!checkCache.equals(""))
					return;

				values.put(ORIGINAL_PATH, originalpath);
				values.put(CACHED_PATH, cachepath);

				resolver.insert(EMarketingContentProvider.IMAGE_CONTENT_URI,
						values);
			}
		}.start();

	}
}
